package com.wswy.wzcx.utils;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.PermissionChecker;

import java.util.ArrayList;
import java.util.List;

public class PermissionHelper {

    private PermissionListener mPermissionListener;
    private Activity mActivity;
    private static final int REQUEST_CODE = 100;
    private static final int ACTION_APPLICATION_DETAILS_SETTINGS_CODE = 202;
    private String[] mPermissions = {
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };
    private List<String> mPermissionList = new ArrayList<>();

    public PermissionHelper(Activity activity) {
        mActivity = activity;
    }

    public void applyPermissions() {
        mPermissionList.clear();
        //逐个判断你要的权限是否已经通过
        for (int i = 0; i < mPermissions.length; i++) {
            if (PermissionChecker.checkSelfPermission(mActivity, mPermissions[i]) != PackageManager.PERMISSION_GRANTED) {
                mPermissionList.add(mPermissions[i]);
            }
        }
        //申请权限
        if (mPermissionList.size() > 0) {//有权限没有通过，需要申请
            String[] strings = new String[mPermissionList.size()];
            ActivityCompat.requestPermissions(mActivity, mPermissionList.toArray(strings), REQUEST_CODE);
        } else {
            //说明权限都已经通过，可以做你想做的事情去
            if (mPermissionListener != null) {
                mPermissionListener.onApplyPerission();
            }
        }
    }

    /**
     * 动态权限回调
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    public void onRequestPermissionsResult(final int requestCode, @NonNull final String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == REQUEST_CODE) {
            boolean hasPermissionDismiss = false;
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults[i] == -1) {
                    hasPermissionDismiss = true;
                }
            }
            //如果有权限没有被允许
            if (hasPermissionDismiss) {
                AlertDialog.Builder builder = new AlertDialog.Builder(mActivity)
                        .setTitle("权限申请")
                        .setMessage("请在打开的窗口的权限中开启手机、存储空间权限，以正常使用本应用")
                        .setPositiveButton("去设置", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                openApplicationSettings(ACTION_APPLICATION_DETAILS_SETTINGS_CODE);
                            }
                        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                mActivity.finish();
                            }
                        });
                builder.setCancelable(false);
                builder.show();
            } else {
                if (mPermissionListener != null) {
                    mPermissionListener.onApplyPerission();
                }
            }
        }
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case ACTION_APPLICATION_DETAILS_SETTINGS_CODE:
                if (isAllRequestedPermissionGranted()) {
                    if (mPermissionListener != null) {
                        mPermissionListener.onApplyPerission();
                    }
                } else {
                    mActivity.finish();
                }
                break;
        }
    }

    /**
     * 判断是否所有的权限都被授权了
     *
     * @return
     */
    public boolean isAllRequestedPermissionGranted() {
        for (String model : mPermissions) {
            if (PackageManager.PERMISSION_GRANTED != PermissionChecker.checkSelfPermission(mActivity, model)) {
                return false;
            }
        }
        return true;
    }

    /**
     * 打开应用设置界面
     *
     * @param requestCode 请求码
     * @return
     */
    private void openApplicationSettings(int requestCode) {
        try {
            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:" + mActivity.getPackageName()));
            intent.addCategory(Intent.CATEGORY_DEFAULT);
            mActivity.startActivityForResult(intent, requestCode);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void setPermissionListener(PermissionListener permissionListener) {
        this.mPermissionListener = permissionListener;
    }

    public interface PermissionListener {
        void onApplyPerission();
    }

}
